/**
 * index.js
 */
Page({
  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    canSearch: false,
    isEmpty: false,
    result: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  bindinput(val) {
    this.setData({
      value: val.detail.value,
      canSearch: val.detail.value.length >= 5 ? true : false,
      isEmpty: false,
      result: []
    });
  },

  deleteValue() {
    this.setData({
      value: "",
      canSearch: false,
      isEmpty: false,
      result: []
    });
  },

  comfirm() {
    if (!this.data.canSearch) {
      return;
    }
    this.search(this.data.value);
  },

  search(value) {
    wx.request({
      url: "https://appapi.jzdoctor.com/apijson/vaccbatch_search",
      data: {
        batch_no: value,
      },
      header: { "content-type": "application/json" },
      method: "POST",
      dataType: "json",
      responseType: "text",
      success: (res) => {
        const { code, data } = res.data || {};
        console.log('code, data: ', code, data);
        if (+code === 0 && data && data.length > 0) {
          const result = this.adapterData(data || []);
          this.setData({
            result,
            isEmpty: false
          })
        } else {
          this.setData({
            isEmpty: true,
            result: []
          })
        }
      },
      fail: () => {
        this.setData({
          isEmpty: true,
          result: []
        })
      },
    });
  },

  adapterData(data){
    return data.map((item) => {
      return {
        id: +item.id,
        data: [
          {
            label: "疫苗名称:",
            value: item.name,
          },
          {
            label: "疫苗规格:",
            value: item.size,
          },
          {
            label: "疫苗批号:",
            value: item.batch_no,
          },
          {
            label: "签发量:",
            value: item.quantity,
          },
          {
            label: "有效期至:",
            value: item.expiry_date,
          },
          {
            label: "生产企业:",
            value: item.company,
          },
          {
            label: "证书编号:",
            value: item.certificate_no,
          },
          {
            label: "签发日期:",
            value: item.issue_date,
          },
        ],
      };
    });
  }
});
